package com.olddriver.crm.web.controller;

import com.olddriver.crm.annotation.PermissionName;
import com.olddriver.crm.domain.Mechanism;
import com.olddriver.crm.page.PageResult;
import com.olddriver.crm.query.MechanismQueryObject;
import com.olddriver.crm.service.IMechanismService;
import com.olddriver.crm.util.JsonResult;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;

@Controller
@RequestMapping("mechanism")
public class MechanismControllerr {
    @Autowired
    private IMechanismService mechanismService;


    @RequiresPermissions("mechanism:list")
    @PermissionName("查看机构")
    @RequestMapping("list")
    public String list() {
        return "mechanism/list";
    }

    @RequestMapping("listAll")
    @ResponseBody
    public List<Mechanism> listAll() {
        return mechanismService.selectAll();
    }

    @RequestMapping("query")
    @RequiresPermissions("mechanism:query")
    @PermissionName("机构列表")
    @ResponseBody
    public PageResult query(MechanismQueryObject qo) {
        PageResult result = mechanismService.query(qo);
        return result;
    }

    @ResponseBody
    @RequestMapping("saveOrUpdate")
    @RequiresPermissions("mechanism:saveOrUpdate")
    @PermissionName("机构编辑")
    public JsonResult saveOrUpdate(Mechanism mechanism) {
        Long id = mechanism.getId();
        try {
            if (id != null) {
                mechanism.setState(true);
                mechanismService.updateByPrimaryKey(mechanism);
            } else {
                mechanism.setState(true);
                mechanismService.insert(mechanism);
            }
            return JsonResult.success();
        } catch (Exception e) {
            e.printStackTrace();
            return JsonResult.faliure();
        }
    }

    @ResponseBody
    @RequestMapping("changeState")
    @RequiresPermissions("mechanism:saveOrUpdate")
    @PermissionName("机构编辑")
    public JsonResult changeState(Long id) {
        try {
            if(id !=null){
                mechanismService.changeState(id);
            }
            return JsonResult.success();
        } catch (Exception e) {
            e.printStackTrace();
            return JsonResult.faliure();
        }
    }

    @RequestMapping("mech")
    @ResponseBody
    public List<Mechanism> mech(){
        return mechanismService.selectAll();
    }

    @RequestMapping("selectByPrimaryKey")
    @ResponseBody
    public Mechanism selectByPrimaryKey(Long mechId){
        return mechanismService.selectByPrimaryKey(mechId);
    }

}
